package l1j.opqlo.Server.etcitem;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.opqlo.Server.L1World.WorldClan;
import l1j.server.Config;
import l1j.server.server.datatables.CharacterTable;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.datatables.LetterTable;
import l1j.server.server.datatables.lock.CharItemsReading;
import l1j.server.server.model.L1Clan;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1PcInventory;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_Letter;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.serverpackets.S_SkillSound;
import l1j.server.server.serverpackets.S_UseMap;

/**
 * 聖誕卡片40730 情人節卡片40731 白色情人節卡片40732
 */
public class Card {

	/** 空的魔法卷軸 LV1~LV5 */

	private final static Logger _log = Logger.getLogger(Card.class.getName());

	public static void begin(final int letterCode, final String letterReceiver,
			final byte[] letterText, final L1PcInstance pc,
			final L1ItemInstance l1iteminstance) {

		final int itemId = l1iteminstance.getItemId();

		if (itemId >= 40373 && itemId <= 40390) {
			pc.sendPackets(new S_UseMap(pc, l1iteminstance.getId(),
					l1iteminstance.getItem().getItemId()));
		} else if (itemId == 40310 || itemId == 40730 || itemId == 40731
				|| itemId == 40732) { // 便箋(未使用)
			if (writeLetter(itemId, pc, letterCode, letterReceiver, letterText)) {
				pc.getInventory().removeItem(l1iteminstance, 1);
			}
		} else if (itemId == 40311) { // 血盟便箋(未使用)
			if (writeClanLetter(itemId, pc, letterCode, letterReceiver,
					letterText)) {
				pc.getInventory().removeItem(l1iteminstance, 1);
			}
		} else if (itemId == 49016 || itemId == 49018 || itemId == 49020
				|| itemId == 49022 || itemId == 49024) { // 便箋(未開封)
			pc.sendPackets(new S_Letter(l1iteminstance));
			l1iteminstance.setItemId(itemId + 1);
			pc.getInventory().updateItem(l1iteminstance,
					L1PcInventory.COL_ITEMID);
			pc.getInventory()
					.saveItem(l1iteminstance, L1PcInventory.COL_ITEMID);

		}

	}

	private static void saveLetter(final int itemObjectId, final int code,
			final String sender, final String receiver, final byte[] text) {// 日付を取得する
		final SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd");
		final TimeZone tz = TimeZone.getTimeZone(Config.TIME_ZONE);
		final String date = sdf.format(Calendar.getInstance(tz).getTime());
		// subjectとcontentの區切り(0x00 0x00)位置を見つける
		int spacePosition1 = 0;
		int spacePosition2 = 0;
		for (int i = 0; i < text.length; i += 2) {
			if (text[i] == 0 && text[i + 1] == 0) {
				if (spacePosition1 == 0) {
					spacePosition1 = i;
				} else if (spacePosition1 != 0 && spacePosition2 == 0) {
					spacePosition2 = i;
					break;
				}
			}
		}

		// letterテーブルに書き迂む
		final int subjectLength = spacePosition1 + 2;
		int contentLength = spacePosition2 - spacePosition1;
		if (contentLength <= 0) {
			contentLength = 1;
		}
		final byte[] subject = new byte[subjectLength];
		final byte[] content = new byte[contentLength];
		System.arraycopy(text, 0, subject, 0, subjectLength);
		System.arraycopy(text, subjectLength, content, 0, contentLength);
		LetterTable.getInstance().writeLetter(itemObjectId, code, sender,
				receiver, date, 0, subject, content);
	}

	private static boolean sendLetter(final L1PcInstance pc, final String name,
			final L1ItemInstance item, final boolean isFailureMessage) {
		final L1PcInstance target = L1World.getInstance().getPlayer(name);
		if (target != null) {
			if (target.getInventory().checkAddItem(item, 1) == L1Inventory.OK) {
				target.getInventory().storeItem(item);
				target.sendPackets(new S_SkillSound(target.getId(), 1091));
				target.sendPackets(new S_ServerMessage(428)); // 手紙が屆きました。
			} else {
				if (isFailureMessage) {// 相手のアイテムが重すぎるため、これ以上あげられません。
					pc.sendPackets(new S_ServerMessage(942));
				}
				return false;
			}
		} else {
			if (CharacterTable.doesCharNameExist(name)) {
				try {
					final int targetId = CharacterTable.getInstance()
							.restoreCharacter(name).getId();
					if (CharItemsReading.get().getItemCount(targetId) < 180) {
						CharItemsReading.get().storeItem(targetId, item);
					} else {
						if (isFailureMessage) {// 相手のアイテムが重すぎるため、これ以上あげられません。
							pc.sendPackets(new S_ServerMessage(942));
						}
						return false;
					}
				} catch (final Exception e) {
					_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
				}
			} else {
				if (isFailureMessage) {
					pc.sendPackets(new S_ServerMessage(109, name)); // %0という名前の人はいません。
				}
				return false;
			}
		}
		return true;
	}

	private static boolean writeClanLetter(final int itemId,
			final L1PcInstance pc, final int letterCode,
			final String letterReceiver, final byte[] letterText) {
		L1Clan targetClan = null;
		for (final L1Clan clan : WorldClan.get().getAllClans()) {
			if (clan.getClanName().toLowerCase()
					.equals(letterReceiver.toLowerCase())) {
				targetClan = clan;
				break;
			}
		}
		if (targetClan == null) {
			pc.sendPackets(new S_ServerMessage(434)); // 受信者がいません。
			return false;
		}

		final String memberName[] = targetClan.getAllMembers();
		for (final String element : memberName) {
			final L1ItemInstance item = ItemTable.getInstance().createItem(
					49016);
			if (item == null) {
				return false;
			}
			item.setCount(1);
			if (sendLetter(pc, element, item, false)) {
				saveLetter(item.getId(), letterCode, pc.getName(), element,
						letterText);
			}
		}
		return true;
	}

	private static boolean writeLetter(final int itemId, L1PcInstance pc,
			final int letterCode, final String letterReceiver,
			final byte[] letterText) {

		int newItemId = 0;
		if (itemId == 40310) {
			newItemId = 49016;
		} else if (itemId == 40730) {
			newItemId = 49020;
		} else if (itemId == 40731) {
			newItemId = 49022;
		} else if (itemId == 40732) {
			newItemId = 49024;
		}
		final L1ItemInstance item = ItemTable.getInstance().createItem(
				newItemId);
		if (item == null) {
			return false;
		}
		item.setCount(1);

		if (sendLetter(pc, letterReceiver, item, true)) {
			saveLetter(item.getId(), letterCode, pc.getName(), letterReceiver,
					letterText);
		} else {
			return false;
		}
		return true;
	}
}
